package com.sgj.controller;

import com.sgj.service.BlogService;
import com.sgj.service.TagService;
import com.sgj.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author 沈国纪
 * @date 2021/3/28 19:59
 */

@Controller
public class IndexController {

	private static final String INDEX = "index";
	private static final String SEARCH = "search";
	private static final String BLOG = "blog";

	@Autowired
	private BlogService blogService;

	@Autowired
	private TypeService typeService;

	@Autowired
	private TagService tagService;

	/**
	 * 主页面展示
	 * @param pageable
	 * @param model
	 * @return
	 */
	@GetMapping("/")
	public String index(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
	                    Model model) {
		model.addAttribute("page", blogService.listBlog(pageable));
		model.addAttribute("types", typeService.listTypeTop(6));
		model.addAttribute("tags", tagService.listTagTop(6));
		model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(6));
		return INDEX;
	}

	/**
	 * 全局搜索
	 * @param pageable
	 * @param query
	 * @param model
	 * @return
	 */
	@PostMapping("/search")
	public String search(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
	                     @RequestParam("query") String query, Model model) {
		model.addAttribute("page", blogService.listBlog(query, pageable));
		model.addAttribute("query", query);
		return SEARCH;
	}

	/**
	 * 博客内容展示
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/blog/{id}")
	public String blog(@PathVariable Long id, Model model) {
		model.addAttribute("blog", blogService.getAndConvert(id));
		return BLOG;
	}

	/**
	 * 底部动态显示最新的三条博客
	 * @param model
	 * @return
	 */
	@GetMapping("/footer/newblog")
	public String newblogs(Model model) {
		model.addAttribute("newblogs", blogService.listRecommendBlogTop(3));
		return "_fragments :: newblogList";
	}
}
